import axios from 'axios';
import { showMessage } from "./status";   // 引入状态码文件
import { Toast } from '@douyinfe/semi-ui';
// import {ElMessage, ElMessageBox, ElLoading} from 'element-plus'  // 引入el 提示框，这个项目里用什么组件库这里引什么

// const {cookies} = useCookies();

// 设置接口超时时间
axios.defaults.timeout = 30000;
// 请求地址，这里是动态赋值的的环境变量，下一篇会细讲，这里跳过
// @ts-ignore
axios.defaults.baseURL = import.meta.env.VITE_BASE_URL;

//http request 拦截器
axios.interceptors.request.use(
    config => {
        // 配置请求头
        // config.headers = {
        //     // 'Content-Type': 'application/x-www-form-urlencoded',   // 传参方式表单
        //     'Content-Type': 'application/json;charset=UTF-8',        // 传参方式json
        //     // 'token': 'aa53b31ad819523405c638575fcb9f75'           // 这里自定义配置，这里传的是token
        //     token: token
        // };
        const token = '84594377e6d530214b49874fb765fb93';
        console.log(token, 'config of token')
        if (token) {
            config.headers["token"] = token;
        }
        console.log(config, 'config')
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

//http response 拦截器
axios.interceptors.response.use(
    response => {
        console.log(response, 'response')
        // if (response?.data?.code === 401 || response?.data?.code === 402) {
        //     let errTxt = ",是否返回登录？";
        //     ElMessageBox.confirm(response?.data?.msg + errTxt, '提示', {
        //         type: 'warning',
        //         showClose: false,
        //         showCancelButton: false,
        //         closeOnClickModal: false,
        //         closeOnPressEscape: false,
        //     }).then(() => {
        //         const user = useUserStore();
        //         const loginurl = cookies.get('loginurl') || user.userInfo.loginurl;
        //         user.setUserInfo({});
        //         cookies.remove("lstoken");
        //         window.location.href = loginurl
        //     })
        //         .catch(() => {
        //         });
        // }
        return response;
    },
    error => {
        const { response } = error;
        console.log(error, 'error')
        console.log(response, 'response')
        if (response) {
            // 请求已发出，但是不在2xx的范围
            showMessage(response.status);           // 传入响应码，匹配响应码对应信息
            return Promise.reject(response.data);
        } else {
            Toast.warning('网络连接异常,请稍后再试!');
        }
    }
);

// 封装 GET POST 请求并导出
export function request(url = '', params = {}, type = 'POST') {
    //设置 url params type 的默认值
    return new Promise((resolve, reject) => {
        let promise: any;
        if (type.toUpperCase() === 'GET') {
            promise = axios({
                url,
                params
            })
        } else if (type.toUpperCase() === 'POST') {
            promise = axios({
                method: 'POST',
                url,
                data: params,
            })
        }
        //处理返回
        promise.then((res: any) => {
            resolve(res.data)
        }).catch((err: any) => {
            reject(err)
        })
    })
}

export async function callbackChart(url = '', params = {}, signal: AbortSignal, callback: any) {
    const apiUrl = import.meta.env.VITE_BASE_URL + url;
    try {
        const token = '84594377e6d530214b49874fb765fb93';
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'token': token
            },
            body: JSON.stringify(params),
            signal: signal, // 中断请求
        });
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const reader = response.body.getReader();
        callback({ status: response.status, reader });
    } catch (error) {
        if (error.name === 'AbortError') {
            console.log('请求已被主动中断');
        } else {
            console.error('请求出错:', error);
        }
        callback({ status: 500, error: error });
    }
}
